<?php
if (! defined ( 'BASEPATH' ))
	exit ( 'No direct script access allowed' );
/**
 * 用户管理
 *
 * @author chaituan@126.com
 */
class User_model extends MY_Model {
	const sess = 'wechat_user_session';
	function __construct() {
		parent::__construct ();
		$this->table_name = 'user';
	}
	// 登录后存session
	function set_LoginUser($data) {
		return $this->session->set_userdata(self::sess,$data);
	}
	
	// 取登录后的信息
	function get_LoginUser() {
		return $this->session->{self::sess};
	}
	
	// 获取用户信息通过id或者openid
	function get_user($key, $value) {
		if ($key == 'id') {
			$where ['id'] = $value;
		} else {
			$where ['openid'] = $value;
		}
		$item = $this->getItem ( $where );
		return $item;
	}
	
	// 更新用户的session 根据id或者openid
	function update_usersession($key, $value) {
		$item = self::get_user ( $key, $value );
		self::set_LoginUser ( $item );
	}
	
	//使用数组更新session
	function up_user_session($data){
		$user = self::get_LoginUser();
		foreach ($user as $key=>$v){
			if(array_key_exists($key, $data)){
				$new[$key] = $data[$key];
			}else{
				$new[$key] = $v;
			}
		}
		self::set_LoginUser($new);
	}
	//更新数据库和session
	function updates_se($data,$where){
		$r = $this->updates($data, $where);
		$this->up_user_session($data);
		return $r;
	}
	
	function fx_fl($order){
		$this->load->model(array('admin/Earnings_model','admin/Goods_model'));
		$goods = $this->Goods_model->getItem(array('id'=>$order['gid']));
		$price = $goods['price'];	
		$earnings = array('p_1'=>$goods['f_1'],'p_2'=>$goods['f_2'],'p_3'=>$goods['f_3']);
		$user = $this->getItem(array('id'=>$order['uid']));
		$t = time();
		if($user){
			$e_detail = '';
			$percentage1 = $earnings['p_1'];//一级的百分比
			if($percentage1){//一级
				$uid_1 = $user['p_1'];//上一级id
				if($uid_1){
					$money = strpos($percentage1,'元')?explode('元', $percentage1)[0]:$price * ($percentage1/100);
					$e_detail[] = array('uid'=>$uid_1,'cid'=>$user['id'],'money'=>$money,'src'=>'下级分成','ands'=>'+','addtime'=>$t);
				}
			}
			$percentage2 = $earnings['p_2'];//二级的百分比
			if($percentage2){//二级
				$uid_2 = $user['p_2'];//上二级id
				if($uid_2){
					$money = strpos($percentage2,'元')?explode('元', $percentage2)[0]:$price * ($percentage2/100);
					$e_detail[] = array('uid'=>$uid_2,'cid'=>$user['id'],'money'=>$money,'src'=>'下级分成','ands'=>'+','addtime'=>$t);
				}
			}
			$percentage3 = $earnings['p_3'];//二级的百分比
			if($percentage3){//二级
				$uid_3 = $user['p_3'];//上二级id
				if($uid_3){
					$money = strpos($percentage3,'元')?explode('元', $percentage3)[0]:$price * ($percentage3/100);
					$e_detail[] = array('uid'=>$uid_3,'cid'=>$user['id'],'money'=>$money,'src'=>'下级分成','ands'=>'+','addtime'=>$t);
				}
			}
			if($e_detail){
				$this->Earnings_model->add_batch($e_detail);//批量添加一级和二级添加明细
			}
		}
	}
	
	// 退出系统
	function logout() {
		$this->session->sess_destroy ();
		redirect(site_url('wechat/tips/logout'));
	}
}